/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.net.greenet.device.logic;

import cn.net.greenet.common.db_service.BaseDao;
import cn.net.greenet.common.policy_service.PolicySupport;
import cn.net.greenet.db.HibernateUtil;
import cn.net.greenet.db.bean.Dpiendpointbean;
import cn.net.greenet.db.bean.Messageincominglog;

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 * @author LiuShang
 * @date 2014-11-3 14:57:48
 */
public class DeviceManagementImpl extends BaseDao implements IDeviceManagement {

    String sql = null;
    Object[] params = {};
    JSONArray jSONArray = null;
    JSONObject jSONObject = null;
    int verify = 0;

    public static void main(String[] args) {
        DeviceManagementImpl iDeviceManagement = new DeviceManagementImpl();
//        System.out.println(iDeviceManagement.getDevList());
        /**
         * *****创建（编辑）设备实例*******
         */
//        System.out.println(iDeviceManagement.editDevInstance("creat", "g555", "g555", "123", "g44442", "g7777", "50001", "1", "2", "0", "描述"));
        /**
         * *********删除设备实例*************
         */
//        System.out.println(iDeviceManagement.deleteDevInstance("g555"));
        /**
         * **********指定设备启用/停用***********
         */
//        System.out.println(iDeviceManagement.editDevUse("g555", "1"));
        /**
         * *************验证添加设备的名称是否唯一**************
         */
//        System.out.println(iDeviceManagement.verifyDevName("g55"));
        /**
         * ******************getDevPolicyBankInfo*******************
         */
//        System.out.println(iDeviceManagement.getDevPolicyBankInfo("1"));
        /**
         * ********************获取每类策略策略库信息***************************
         */
//        System.out.println(iDeviceManagement.getEveryPolicyBank());
        /**
         * *******************写入静态设备**************
         */
//        iDeviceManagement.write();
        
    }

    @Override
    public JSONArray getDevList() {
        try {
            sql = "select * from dpiendpointbean;";
            System.out.println(sql);
            rs = this.executeSQL(sql, params);
            jSONArray = new JSONArray();
            while (rs.next()) {
                jSONObject = new JSONObject();
                String name = rs.getString("names");
                int id = rs.getInt("id");
                boolean isCCOn = rs.getBoolean("isClientChannelConnected");
                boolean isSCOn = rs.getBoolean("isServerChannelConnected");
                String ip = rs.getString("masterIp");
                jSONObject.put("name", name);
                jSONObject.put("ip", ip);
                jSONObject.put("id", id);
                jSONObject.put("isCCOn", isCCOn);
                jSONObject.put("isSCOn", isSCOn);
                jSONArray.add(jSONObject);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            this.close();
        }
        return jSONArray;
    }

    @Override
    public JSONObject getDevStaticInfo(String id) {
        sql = "";
        return null;
    }

    @Override
    public JSONObject getDevDynamicInfo(String id) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public JSONArray getDevPolicyBankInfo(String id) {
        try {
            jSONArray = new JSONArray();
            sql = "SELECT policy.instanceName,policy.PolicyRepositoryType_messageType from Dpiendpointbean as dpib \n"
                    + "inner join DPIEndPointBean_has_PolicyRepositoryInstance as dpip on dpib.id=dpip.DPIEndPointBean_id\n"
                    + "inner join PolicyRepositoryInstance as policy on dpip.PolicyRepositoryInstance_id=policy.id where dpib.id=?;";
            Object[] params = {id};
            rs = this.executeSQL(sql, params);
            while (rs.next()) {
                jSONObject = new JSONObject();
                String Message_Type = rs.getString("PolicyRepositoryType_messageType");
                String strategy_name = rs.getString("instanceName");
                jSONObject.put("Message_Type", Message_Type);
                jSONObject.put("strategy_name", strategy_name);
                jSONObject.put("version", PolicySupport.getInstance().getApi().getHeadVersion(Message_Type, strategy_name));
                jSONArray.add(jSONObject);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            this.close();
        }
        return jSONArray;
    }

    @Override
    public JSONObject editDevInstance(String id, String Dev_Name, String Dev_IP, String Probe_Type, String DeploySiteName, String IDC_HouseID, String port, String enabled, String isServerChannelConnected, String isClientChannelConnected, String description) {
        jSONObject = new JSONObject();
        if ("create".equals(id)) {
            Object[] params = {Dev_Name, Dev_IP, Probe_Type, DeploySiteName, IDC_HouseID, port, enabled, isServerChannelConnected, isClientChannelConnected, description};
            sql = "insert into dpiendpointbean (name,masterIp,probeType,deploySiteName,idcHouseId,port,enabled,isServerChannelConnected,isClientChannelConnected,description)values (?,?,?,?,?,50000, 0, 0, 0,?);";
            //             sql = "insert into dpiendpointbean (name,masterIp,probeType,deploySiteName,idcHouseId)values (?,?,?,?,?);";
            verify = executeUpdate(sql, params);

        } else if (id.matches("[0-9]*")) {
            Object[] params = {Dev_Name, Dev_IP, Probe_Type, DeploySiteName, IDC_HouseID, port, enabled, isServerChannelConnected, isClientChannelConnected, description, id};
            sql = "update dpiendpointbean set name=?,masterIp=?,probeType=?,deploySiteName=?,port=?,idcHouseId=?,enabled=?,isServerChannelConnected=?,isClientChannelConnected=? where id=?";
            verify = this.executeUpdate(sql, params);
        } else {
            System.out.println("错误数据");
        }
        System.out.println(sql);
        if (verify > 0) {
            jSONObject.put("result", "true");
        } else {
            jSONObject.put("result", "false");
        }
        // （4）处理执行结果
        this.close();
        return jSONObject;
    }

    @Override
    public JSONObject deleteDevInstance(String Dev_Name) {
        jSONObject = new JSONObject();
        sql = "delete from dpiendpointbean where name = ?";
        System.out.println(sql);
        Object[] params = {Dev_Name};
        verify = this.executeUpdate(sql, params);
        if (verify > 0) {
            jSONObject.put("result", "true");
        } else {
            jSONObject.put("result", "false");
        }
        // （4）处理执行结果
        this.close();
        return jSONObject;
    }

    @Override
    public JSONObject editDevPolicyBank(String Dev_Name, String Message_Type, String strategy_name) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public JSONArray getEveryPolicyBank() {
        try {
            jSONArray = new JSONArray();
            sql = "SELECT policy.id,policy.instanceName,policy.PolicyRepositoryType_messageType from Dpiendpointbean as dpib \n"
                    + "inner join DPIEndPointBean_has_PolicyRepositoryInstance as dpip on dpib.id=dpip.DPIEndPointBean_id\n"
                    + "inner join PolicyRepositoryInstance as policy on dpip.PolicyRepositoryInstance_id=policy.id;";
            rs = this.executeSQL(sql, params);
            while (rs.next()) {
                jSONObject = new JSONObject();
                int id = rs.getInt("id");
                String Message_Type = rs.getString("PolicyRepositoryType_messageType");
                String strategy_name = rs.getString("instanceName");
                jSONObject.put("id", id + "");
                jSONObject.put("Message_Type", Message_Type);
                jSONObject.put("strategy_name", strategy_name);
                jSONArray.add(jSONObject);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            this.close();
        }
        return jSONArray;
    }

    @Override
    public JSONObject editDevUse(String Dev_Name, String device_status) {
        jSONObject = new JSONObject();
        sql = "update dpiendpointbean set enabled=? where name = ?";
        System.out.println(sql);
        Object[] params = {device_status, Dev_Name};
        verify = this.executeUpdate(sql, params);
        if (verify > 0) {
            jSONObject.put("result", "true");
        } else {
            jSONObject.put("result", "false");
        }
        this.close();
        return jSONObject;
    }

    @Override
    public JSONObject verifyDevName(String device_name) {
        try {
            jSONObject = new JSONObject();
            sql = "select name from dpiendpointbean where name= ?";
            System.out.println(sql);
            Object[] params = {device_name};
            rs = this.executeSQL(sql, params);
            if (rs.next()) {
                jSONObject.put("result", "true");
            } else {
                jSONObject.put("result", "false");
            }
            return jSONObject;
        } catch (SQLException ex) {
            Logger.getLogger(DeviceManagementImpl.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            this.close();
        }
        return jSONObject;
    }

    public void StaticDevice(byte[] msg) {
        
        int ptr = 0;
        int SoftwareVersion = (int) ByteConvert.bytesToUint(Arrays.copyOfRange(msg, ptr, ptr + 4));//DPI软件版本号
        ptr = ptr + 4;
        int Probe_Type = msg[ptr];//DPI采集类型
        ptr++;
        int DeploySiteNameLength = msg[ptr];//本DPI设备部署站点名长度
        ptr++;
        String DeploySiteName = new String(Arrays.copyOfRange(msg, ptr, ptr + DeploySiteNameLength));//本DPI设备部署站点名
        ptr = ptr + DeploySiteNameLength;
        int IDC_HouseID_Length = msg[ptr];//EU 设 备 部 署 机 房HouseID的长度 
        ptr++;
        String IDC_HouseID = new String(Arrays.copyOfRange(msg, ptr, ptr + IDC_HouseID_Length));//本DPI设备部署站点名称
        ptr = ptr + IDC_HouseID_Length;
        int Deploy_Mode = msg[ptr];//本DPI设备在现网中的部署模式
        ptr++;
        int Total_Capability = ByteConvert.bytesToUshort(Arrays.copyOfRange(msg, ptr, ptr + 2));//DPI设备总分析能力( 以Gbps为单位)，单向
        ptr = ptr + 2;
        int SlotNum = msg[ptr];//DPI设备总槽位数  
        ptr++;
        int PreProcSlotNum = msg[ptr];//DPI设备预处理模块占用槽位数
        ptr++;
        int AnalysisSlotNum = msg[ptr];//DPI设备分析模块占用槽位数
        ptr++;
        int GPSlotNum = msg[ptr];//DPI 通用 (General Purpose)模块占用槽位数
        ptr++;
        int PortsTypeNum = msg[ptr];//本DPI设备所配备的端口类型数
        ptr++;
        for (int i = 0; i < PortsTypeNum; i++) {
            int PortType = msg[ptr];//本DPI设备现有端口类型
            ptr++;
            int PortsNum = msg[ptr];//属于本类型的端口数
            ptr++;
            for (int j = 0; j < PortsNum; j++) {
                int PortNo = msg[ptr];//本端口的编号
                ptr++;
                int PortDescLength = msg[ptr];//本端口描述信息长度
                ptr++;
                String PortDescription = new String(Arrays.copyOfRange(msg, ptr, ptr + PortDescLength));//本端口描述信息
                ptr = ptr + PortDescLength;
                int M_LinkID = msg[ptr];//本端口监控链路编号
                ptr++;
                int M_LinkDescLength = msg[ptr];//本端口监控链路描述信息长度
                ptr++;
                String M_LinkDesc = new String(Arrays.copyOfRange(msg, ptr, ptr + M_LinkDescLength));//监控链路描述信息
                ptr = ptr + M_LinkDescLength;
            }
        }
    }

    public void DynamicDevice(byte[] msg) {
        int ptr = 0;
        int Total_PostNum = msg[ptr];//本DPI设备的总端口数
        ptr++;
        for (int i = 0; i < Total_PostNum; i++) {
            int PortNo = msg[ptr];//端口编号
            ptr++;
            int PortInfoLength = msg[ptr];//端口描述信息长度
            ptr++;
            String PortInfo = new String(Arrays.copyOfRange(msg, ptr, ptr + PortInfoLength));//端口描述信息
            ptr = ptr + PortInfoLength;
            int PortUsage = msg[ptr];//本端口利用率
            ptr++;
        }
        int Total_CPU_Num = ByteConvert.bytesToUshort(Arrays.copyOfRange(msg, ptr, ptr + 2));//本DPI设备中所含的CPU数
        ptr = ptr + 2;
        for (int i = 0; i < Total_CPU_Num; i++) {
            int CPU_No = ByteConvert.bytesToUshort(Arrays.copyOfRange(msg, ptr, ptr + 2));//CPU编号
            ptr = ptr + 2;
            int CPU_Usage = msg[ptr];//本CPU利用率
            ptr++;
        }
    }

    public void write() {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
        try {
            Messageincominglog bean = new Messageincominglog();
            bean.setMessageType("0xc5");
            bean.setMessageNo(1);
            bean.setMessageSequenceNo(1l);
            bean.setMessageSerialNo(1l);
            bean.setFromIp("192.168.1.1.1");
            DataInputStream dis = new DataInputStream(new FileInputStream("E:\\Documents\\NetBeansProjects\\Yituo_N_detection\\src\\main\\resources\\uc\\6.4.6.dat"));
            int size = dis.available();
            byte[] bs = new byte[size];
            int rs = 0;
            while ((rs = dis.read(bs)) != -1) {
            }
            bean.setPacket(bs);
            bean.setTime(new java.sql.Timestamp(System.currentTimeMillis()));
            Dpiendpointbean dpi = (Dpiendpointbean) session.get(Dpiendpointbean.class, 16);
            bean.setDpiendpointbean(dpi);
            dis.close();
            session.save(bean);
            tx.commit();

        } catch (Exception ex) {
            ex.printStackTrace();
            tx.rollback();
            Logger.getLogger(DeviceManagementImpl.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            session.close();
        }

    }

}
